// KNPSK // Knapsack Problem // Author: Constantine Sokol // Complexity : O( N log N ) // Expected Verdict: AC #include #include #include #include using namespace std; const int maxn = 100000 + 5; int n, curW = 0, sumW = 0; priority_queue< long long > ones, twos, taken_ones, taken_twos; long long sumC = 0; int main() { scanf("%d", &n); for ( int i = 1; i <= n; i++ ) { int w, c; scanf("%d%d", &w, &c); if ( w == 1 ) ones.push( 1ll * c ); if ( w == 2 ) twos.push( 1ll * c ); sumW += w; } for ( int w = 1; w <= sumW; w++ ) { while ( curW + 1 <= w && ones.size() > 0 ) { long long c = ones.top(); ones.pop(); taken_ones.push( -c ); sumC += c; curW += 1; } while ( curW + 2 <= w && twos.size() > 0 ) { long long c = twos.top(); twos.pop(); taken_twos.push( -c ); sumC += c; curW += 2; } while ( true ) { if ( taken_ones.size() < 1 ) break; if ( twos.size() < 1 ) break; if ( curW + 1 > w ) break; long long a = -taken_ones.top(); taken_ones.pop(); long long b = twos.top(); twos.pop(); if ( a < b ) { taken_twos.push( -b ); ones.push( a ); sumC += b - a; curW += 1; } else { taken_ones.push( -a ); twos.push( b ); break; } } while ( true ) { if ( taken_ones.size() < 2 ) break; if ( twos.size() < 1 ) break; long long a = -taken_ones.top(); taken_ones.pop(); long long b = -taken_ones.top(); taken_ones.pop(); long long c = twos.top(); twos.pop(); if ( a + b < c ) { taken_twos.push( -c ); ones.push( a ); ones.push( b ); sumC += c - ( a + b ); } else { taken_ones.push( -a ); taken_ones.push( -b ); twos.push( c ); break; } } printf("%lld ", sumC ); } return 0; }